// @ts-nocheck
import React, { useState, useEffect } from 'react';
import { Button, Input, Form } from 'react-vant';
import { Toast, NavBar } from 'antd-mobile';
import { ExclamationOutline } from 'antd-mobile-icons';
import { history } from 'umi';

import server from '@/utlis/server';
import './index.less';
import '@/pages/golobo.less';
import 'lib-flexible';
import axios from 'axios';
export default function index(props) {
  let [dispbtn, setdispbtn] = useState(false);
  let [logonbtn, setlogonbtn] = useState(false);
  let [yanzhen, setyanzhen] = useState(false);
  let [logintype, setlogintype] = useState('phone');
  let [form] = Form.useForm();
  let [users, setusers] = useState({
    phone: '19831031157',
    code: '',
  });
  let Toastshow = () => {
    let titile = logintype == 'phone' ? '手机号' : '邮箱';
    Toast.show({
      content: `不可修改为当前绑定的${titile}`,
      icon: <ExclamationOutline />,
    });
  };
  const onFinish = async (values) => {
    // console.log(values);
    let { data } = await server.post('/editphone', { phone: values.phone });
    localStorage.setItem('token', data.token);
    // console.log(data);

    history.push({
      pathname: '/userinfo',
      state: {
        _id: data.user._id,
      },
    });
  };
  const back = () => {
    history.go(-1);
  };
  const phonetest = async () => {
    let { data } = await server.post('/phoneapi', { phone: users.phone });
    // console.log(data.code);

    setyanzhen(data.code);
  };
  //发送验证吗
  const sendcode = (e) => {
    // let sec = 60;

    // phonetest();

    // let timer = setInterval(function () {
    //   // 获取注册按钮的DOM
    //   setdispbtn(true);
    //   var btn = e.target;
    //   sec--;
    //   btn.innerHTML = `<span>重新发送(${sec})</span>`;
    //   //   console.log(btn.innerHTML);
    //   if (sec == 0) {
    //     clearInterval(timer); // 清除定时器
    //     setdispbtn(false); // 按钮恢复可用
    //     btn.innerHTML = '<span>重新发送</span>'; // 设置按钮文本
    //   }
    // }, 1000);
    const options = {
      method: 'POST',
      url: 'http://dfsmsv2.market.alicloudapi.com/data/send_sms_v2',
      headers: {
        Accept: 'application/json',
        'Content-Type': ' application/x-www-form-urlencoded; charset=utf-8',
        Authorization: 'APPCODE 8e31ee16f746459ea8f5bb21376ea6f8',
        'content-type': 'application/x-www-form-urlencoded',
      },
      data: {
        content: 'code:123456',
        phone_number: `${users.phone}`,
        template_id: 'TPL_0000',
      },
    };

    server
      .request(options)
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.error(error);
      });
  };

  useEffect(() => {
    if (users.phone != '') {
      setdispbtn(false);
    } else {
      setdispbtn(true);
    }
  }, [users.phone]);

  useEffect(() => {
    if (users.code != '') {
      // console.log(1111);

      setlogonbtn(false);
    } else {
      setlogonbtn(true);
    }
  }, [users.code]);
  let getuser = async () => {
    let id = props.location.state._id;
    let { data } = await server.get('/userinfo/' + id);
    // console.log(data);
    users.phone = data.data.phone;
    // console.log(data.data.phone);

    setusers({ ...users });
  };
  useEffect(() => {
    getuser();
  }, []);

  return (
    <div className="editemail_phone_box">
      <NavBar onBack={back}>{props.location.state.title}</NavBar>
      <div className="form_box">
        <Form
          form={form}
          onFinish={onFinish}
          footer={
            <div style={{ margin: '16px 16px 0' }} className="form_btn">
              <Button
                round
                type="primary"
                block
                disabled={dispbtn}
                onClick={(e) => {
                  sendcode(e);
                }}
              >
                获取验证码
              </Button>
              <Button
                round
                nativeType="submit"
                type="primary"
                block
                disabled={logonbtn}
                onClick={() => {}}
              >
                修改
              </Button>
            </div>
          }
        >
          <Form.Item
            tooltip={{
              message:
                'A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself.',
            }}
            rules={[
              {
                validator: (_, value) => {
                  let phone = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
                  // console.log(phone.test(value));

                  if (phone.test(value)) {
                    setlogintype('phone');
                    return Promise.resolve(true);
                  } else {
                    return Promise.reject(new Error('请输入正确的用户名'));
                  }
                },
                required: true,
              },
            ]}
            name="phone"
            label="手机号"
          >
            <Input
              placeholder="请输入手机号"
              defaultValue={users.phone}
              onChange={(value) => {
                users.phone = value;
                setusers({ ...users });
              }}
            />
          </Form.Item>
          <Form.Item
            rules={[
              {
                validator: (_, value) => {
                  if (value == 123456) {
                    return Promise.resolve(true);
                  }
                  return Promise.reject(new Error('验证码不正确'));
                },
                required: true,
              },
            ]}
            name="code"
            label="验证码"
          >
            <Input
              placeholder="请填写验证码"
              defaultValue={users.code}
              onChange={(value) => {
                users.code = value;
                setusers({ ...users });
              }}
            />
          </Form.Item>
        </Form>
      </div>
    </div>
  );
}
